package com.kgc.kmall.kmallpassportweb.controller;

import com.alibaba.fastjson.JSON;
import com.kgc.kmall.annotations.LoginRequired;
import com.kgc.kmall.bean.Member;
import com.kgc.kmall.service.MemberService;
import com.kgc.kmall.util.HttpclientUtil;
import com.kgc.kmall.util.JwtUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
public class PassportController {

    @Reference
    MemberService memberService;

    @LoginRequired(false)
    @RequestMapping("index")
    public String index(String ReturnUrl, Model model){
model.addAttribute("ReturnUrl",ReturnUrl);
        return "index";
    }

    @RequestMapping("login")
    @ResponseBody
    public String login(String userName, String password, HttpServletRequest request){
            //验证用户名和密码
        Member member=memberService.login(userName,password);
        if (member==null||member.equals("")){
            return "fail";
        }else{
            //生成Jwt
            Long id = member.getId();
            String nickname = member.getNickname();
            Map<String,Object> userMap = new HashMap<>();
            userMap.put("memberId",id);
            userMap.put("nickname",nickname);

            String ip = request.getRemoteUser();
            if (StringUtils.isBlank(ip)||"0:0:0:0:0:0:0:1".equals(ip)){
                ip="127.0.0.1";
            }
          String  token = JwtUtil.encode("2020kmall076", userMap, ip);
            //写入缓存
            memberService.addToken(token,id);
            return  token;
        }
    }

    @RequestMapping("verify")
    @ResponseBody
    public Map<String,Object> verify(String token,String currentIp,HttpServletRequest request){

        // 通过jwt校验token真假
        Map<String,Object> map = new HashMap<>();

        Map<String, Object> decode = JwtUtil.decode(token, "2020kmall076", currentIp);

        if(decode!=null){
            map.put("status","success");
            Object memberId = decode.get("memberId");
            map.put("memberId",memberId);
            map.put("nickname",decode.get("nickname"));
        }else{
            map.put("status","fail");
        }

        return map;
    }

    @RequestMapping("/vlogin")
    public String vlogin(String code,HttpServletRequest request){
        //code接收授权码

        String s3 = "https://api.weibo.com/oauth2/access_token";
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("client_id","761388714");
        paramMap.put("client_secret","a23441914efa3cddf363de126e4de47b");
        paramMap.put("grant_type","authorization_code");
        paramMap.put("redirect_uri","http://passport.kmall.com:8086/vlogin");
        paramMap.put("code",code);// 授权有效期内可以使用，没新生成一次授权码，说明用户对第三方数据进行重启授权，之前的access_token和授权码全部过期
        String access_token_json = HttpclientUtil.doPost(s3, paramMap);

        Map<String,String> access_map = JSON.parseObject(access_token_json,Map.class);

        String access_token = access_map.get("access_token");
        String uid = access_map.get("uid");


        //根据access_token获取用户信息
        // 4 用access_token查询用户信息
        String s4 = "https://api.weibo.com/2/users/show.json?access_token="+access_token+"&uid="+uid;
        String user_json = HttpclientUtil.doGet(s4);
        Map<String,String> user_map = JSON.parseObject(user_json,Map.class);
        System.out.println(user_map);

        // 将用户信息保存数据库，用户类型设置为微博用户
        Member umsMember = new Member();
        umsMember.setSourceType(2);
        umsMember.setAccessToken(code);
        umsMember.setAccessToken(access_token);
        umsMember.setSourceUid(Long.parseLong((String) user_map.get("idstr")));
        umsMember.setCity((String)user_map.get("location"));
        umsMember.setNickname((String)user_map.get("screen_name"));
        Integer g = 0;
        String gender = user_map.get("gender");
        if(gender.equals("m")){
            g = 1;
        }
        umsMember.setGender(g);

        //判断用户是否存在,不存在保存,存在获取对象
        Member member = memberService.selectAllBysourceUid(Long.parseLong(uid));

        if (member==null){
            memberService.add(umsMember);
        }else {
            umsMember=member;
        }

        //生成Jwt
        Long id = umsMember.getId();
        String nickname = umsMember.getNickname();
        Map<String,Object> userMap = new HashMap<>();
        userMap.put("memberId",id);
        userMap.put("nickname",nickname);

        String ip = request.getRemoteUser();
        if (StringUtils.isBlank(ip)||"0:0:0:0:0:0:0:1".equals(ip)){
            ip="127.0.0.1";
        }
        String  token = JwtUtil.encode("2020kmall076", userMap, ip);
        //写入缓存
        memberService.addToken(token,id);

        return "redirect:http://search.kmall.com:8084/index.html?token="+token;
    }
}
